<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <span>{{ $route.query.type == "add" ? '新增应用' : "编辑应用" }}</span>
        <el-button type="primary" :loading="buttonLoading" @click="router.push('/AppManager/Index')">退出</el-button>
      </div>
    </template>

    <div class="add-form" v-loading="loading">
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="100px"
        label-position="left"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="应用名称" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入应用名称"></el-input>
        </el-form-item>

        <el-form-item label="简介" prop="description">
          <el-input v-model="ruleForm.description" placeholder="请输入简介" autosize type="textarea"></el-input>
        </el-form-item>

        <el-form-item label="回调地址" prop="authDomain">
          <el-input v-model="ruleForm.authDomain" placeholder="多个回调域名以;分割"></el-input>
        </el-form-item>
        
        <div class="add-button">
          <el-button type="primary" @click="submitForm(ruleFormRef)" :loading="buttonLoading">
            {{ $route.query.type == "add" ? '新增' : "编辑" }}
          </el-button>
          <el-button @click="resetForm(ruleFormRef)" :loading="buttonLoading">重置</el-button>
        </div>
      </el-form>
    </div>
  </el-card>
</template>

<script>
export default { name: "addApplication" }
</script>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { http } from '@/utils/http/index';
import { ContentTypeEnum } from '@/enums/httpEnum';

/* 路由 */
const router = useRouter()

onMounted(() => {
  if(router.currentRoute.value.query.id){
    getApplicationDetail()
  }
})

/* 详情数据加载动画 */
const loading = ref(false)

/* 查询详情 */
const getApplicationDetail = () => {
  loading.value = true
  http.$GET("/AppManager/GetAppById", { id: router.currentRoute.value.query.id }).then(res => {
    loading.value = false
    if (res.isError) return
    if (!res.result) return
    
    /* 赋值 */
    Object.keys(ruleForm.value).forEach((key)=>{
      if(res.result.content[key] != null){
        ruleForm.value[key] = res.result.content[key];
      }
    })
  }).catch(err => {
    loading.value = false
    ElMessage.warning("查询失败")
  })
}

/* 新增、编辑表单 */
const ruleFormRef = ref(null)

/* 新增、编辑表单数据 */
const ruleForm = ref({
  id: "",
  name: "",
  description: "",
  authDomain: "",
})

/* 回调地址校验 */
const checkAuthDomain = (rule, value, callback) => {
  const reg=/^([hH][tT]{2}[pP]:\/\/|[hH][tT]{2}[pP][sS]:\/\/)(([A-Za-z0-9-~]+)\.)+([A-Za-z0-9-~\/])+$/;
	if(!reg.test(value)){
		callback(new Error('请填写正确的回调地址'))
	} else {
    callback()
  }
}

/* 表单校验规则 */
const rules = reactive({
  name: [
    { required: true, message: '请填写应用名称', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请填写简介', trigger: 'blur' }
  ],
  authDomain: [
    { required: true, message: '请填写回调地址', trigger: 'blur' },
    /* { validator: checkAuthDomain, message: '请填写正确的回调地址', trigger: 'blur' } */
  ],
})

/* 提交新增或编辑时，按钮禁用 */
const buttonLoading = ref(false)

/* 提交 */
const submitForm = (formName) => {
  ruleFormRef.value.validate((valid, fields) => {
    if(valid) {
      buttonLoading.value = true

      let params = JSON.parse(JSON.stringify(ruleForm.value))
      params.des = params.description
      const formData = new FormData()
      for(let k in params) {
        formData.append(k ,params[k])
      }

      http.$POST("/AppManager/EditApp", formData).then(res => {
        buttonLoading.value = false
        if (res.isError) {
          ElMessage.warning('操作失败');
        }else{
          ElMessage.success('操作成功');
          router.push({
            path: "/"
          })
        }
      }).catch(err => {
        buttonLoading.value = false
        ElMessage.warning('操作失败');
      })
    }else{
      ElMessage.warning('请先完成必填项');
    }
  })
}

/* 重置 */
const resetForm = (formName) => {
  ruleFormRef.value.resetFields()
}
</script>

<style lang='scss' scoped>
@import "@/assets/styles/backendElement.scss";
</style>